import { reactive } from 'vue'

// useDBHelp,
import { useStores } from '@naturefw/storage'


export default function findDbManage() {
  
  const dataSource = reactive([])

  const model = {
    findId: 1,
    modId: 1,
    test: '测试数据'
  }

  const { find_test } = useStores('nf-find-db-test')

  
  // 获取一个对象。id：null，获取全部对象
  const get = (id = null) => {
    // const flag = id === null ? '获取全部' : '获取一条'
    // 不设置ID，获取全部对象
    find_test.get(id).then((res) => {
      if (id === null) {
        dataSource.length = 0
        dataSource.push(...res)
      } else {
        model.test = res.test
      }
    })
  }

  // 添加一个对象
  const add = () => {
    model.findId = new Date().valueOf()
    find_test.add(model)
  }

  // 初始化一批数据
  const start = () => {
    find_test.add({
      findId: new Date().valueOf(),
      modId: 1,
      test: '测试数据'
    }).then(() => {
      get()
    })
  }

  // 设置一个对象
  const set = () => {
    model.findId = 123
    model.test = '仓库设置测试:' + new Date().valueOf()
    find_test.set(model).then(() => {
      get()
    })
  }

  // 修改一个对象
  const put = async (id) => {
    model.findId = id
    model.test = '仓库修改测试:' + new Date().valueOf()
    await find_test.put(model).then(() => {})
    get()
  }

  // 删除一个对象
  const del = async (id) => {
    await find_test.del(id).then(() => {})
    get()
  }

  // 查询
  const find = (query) => {
    const _query = {
      test: [401, '22']
    }
    find_test.list(_query).then((res) => {
      console.log('find_test', find_test)
      console.log('res', res)
      dataSource.length = 0
      dataSource.push(...res)
    })
  }

  get()

  return {
    dataSource,
    model,
    start,
    add,
    set,
    put,
    del,
    get,
    find
  }
}